/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
/* eslint no-console: "off" */
/* eslint global-require: "off" */
/* eslint no-param-reassign: ["error", { "props": false }] */

const gulp = require('gulp');
const fs = require('fs');

const rollup = require('rollup');
const buble = require('rollup-plugin-buble');
const replace = require('rollup-plugin-replace');
//const less = require('rollup-plugin-less');

const header = require('gulp-header');
const uglify = require('gulp-uglify');
const sourcemaps = require('gulp-sourcemaps');
const rename = require('gulp-rename');
const bannerVue = require('./banner-vue');

const pkg = require('../package.json');
const version = process.env.VERSION || pkg.version;

function esm({ banner, componentImports, componentExports, registerComponents }) {
  return `
${banner}

import Vue from 'vue';
${componentImports.join('\n')}

export {\n${componentExports.join(',\n')}\n};

export default {
  name: 'jsVue',
  install() {
    ${registerComponents}
  }
}
  `.trim();
}

function buildVue(cb) {
  const env = process.env.NODE_ENV || 'development';
  const buildPath = env === 'development' ? './build' : './packages';
  // const pluginContent = fs.readFileSync(`./${buildPath}/vue/utils/plugin.js`, 'utf-8');

  // /* Replace plugin vars: utils/plugin.js */
  // const newPluginContent = pluginContent
  //   .replace('// IMPORT_LIBRARY', 'import Vue from \'vue\';')
  //   .replace('// IMPORT_COMPONENTS\n', '')
  //   .replace('// REGISTER_COMPONENTS\n', '')
  //   .replace(/EXTEND/g, 'params.Vue || Vue')
  //   .replace(/COMPILER/g, '\'vue\'');

  // fs.writeFileSync(`${buildPath}/vue/utils/plugin.js`, newPluginContent);

  /* Build main components esm module: js-vue.esm.js */
  const files = fs.readdirSync(`${buildPath}/vue/components`).filter(file => file.indexOf('.d.ts') < 0);
  const components = [];
  const componentImports = [];
  const componentExports = [];

  files.forEach(async (fileName) => {
    const componentName = fileName
      .replace('.js', '')
      .split('-')
      .map((word, index) => {
        const capitalized = word[0].toUpperCase() + word.substr(1);
        return index === 0 ? `js${capitalized}` : capitalized;
      })
      .join('');
    components.push({
      name: `js-${fileName.replace('.js', '')}`,
      importName: componentName,
    });
    componentImports.push(`import ${componentName} from './components/${fileName.replace('.js', '')}';`);
    componentExports.push(`  ${componentName}`);

    // // import css add by jack on 20181008
    // const fileNameSlice = fileName
    //   .replace('.js', '')
    //   .split('-')
    //   .map((word, index) => {
    //     return word;
    //   })
    //   .join('');
    // const cssFilePath = `./src/style/css-slice/${fileNameSlice}.css`;
    // if (fs.existsSync(cssFilePath)) {
    //   var data = fs.readFileSync(`${buildPath}/vue/components/${fileName}`);
    //   var injectCssPath = `../../../src/style/css-slice/${fileNameSlice}.css`;
    //   data = `import ${fileNameSlice}CSS from '${injectCssPath}';\n` + data;
    //   fs.writeFileSync(`${buildPath}/vue/components/${fileName}`, data);
    // }
  });

  const registerComponents = components
    .map(c => `Vue.component('${c.name}', ${c.importName});`)
    .join('\n    ');

  const componentsContent = esm({
    banner: bannerVue.trim(),
    componentImports,
    componentExports,
    registerComponents
  });

  fs.writeFileSync(`${buildPath}/vue/js-vue.esm.js`, componentsContent);

  // /* Build esm module bundle: components + plugin -> js-vue.esm.bundle.js */
  // const registerComponents = components
  //   .map(c => `Vue.component('${c.name}', ${c.importName});`)
  //   .join('\n    ');

  // const esmBundlePluginContent = pluginContent
  //   .replace(/ from '\.\//g, ' from \'./utils/')
  //   .replace('// IMPORT_LIBRARY', 'import Vue from \'vue\';')
  //   .replace('// IMPORT_COMPONENTS', `${componentImports.join('\n')}\n`)
  //   .replace('// REGISTER_COMPONENTS', registerComponents)
  //   .replace(/EXTEND/g, 'params.Vue || Vue')
  //   .replace(/COMPILER/g, '\'vue\'');

  // fs.writeFileSync(`${buildPath}/vue/js-vue.esm.bundle.js`, bannerVue + esmBundlePluginContent);

  // /* Build UMD from esm bundle: js-vue.esm.bundle.js -> js-vue.js */
  // rollup.rollup({
  //   input: `${buildPath}/vue/js-vue.esm.bundle.js`,// input: `${buildPath}/vue/js-vue.esm.bundle.js`,
  //   external: ['vue'],
  //   plugins: [
  //     replace({
  //       delimiters: ['', ''],
  //       'process.env.NODE_ENV': JSON.stringify(env), // or 'production'
  //     }),
  //     buble({
  //       objectAssign: 'Object.assign',
  //     })
  //   ],
  // }).then(bundle => bundle.write({
  //   globals: {
  //     vue: 'Vue',
  //   },
  //   strict: true,
  //   file: `${buildPath}/vue/js-vue.js`,
  //   format: 'umd',
  //   name: 'jsVue',
  //   sourcemap: env === 'development',
  //   sourcemapFile: `${buildPath}/vue/js-vue.js.map`,
  //   banner: bannerVue,
  // })).then(() => {
  //   if (env === 'development') {
  //     if (cb) cb();
  //     return;
  //   }
  //   //Minified version
  //   gulp.src(`${buildPath}/vue/js-vue.js`)
  //     .pipe(sourcemaps.init())
  //     .pipe(uglify())
  //     .pipe(header(bannerVue))
  //     .pipe(rename((filePath) => {
  //       filePath.basename += '.min';
  //     }))
  //     .pipe(sourcemaps.write('./'))
  //     .pipe(gulp.dest(`${buildPath}/vue/`))
  //     .on('end', () => {
  //       if (cb) cb();
  //     });
  // }).catch((err) => {
  //   if (cb) cb();
  //   console.log(err);
  // });
}

module.exports = buildVue;
